package com.zhengshang.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.zhengshang.api.domain.*;
import com.zhengshang.api.mapper.*;
import com.zhengshang.api.service.IAppSigninRecordService;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.utils.DateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhengshang.common.annotation.DataScope;
import com.zhengshang.common.constant.UserConstants;
import com.zhengshang.common.core.domain.entity.SysRole;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.exception.CustomException;
import com.zhengshang.common.utils.SecurityUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.system.domain.SysPost;
import com.zhengshang.system.domain.SysUserPost;
import com.zhengshang.system.domain.SysUserRole;
import com.zhengshang.system.mapper.SysPostMapper;
import com.zhengshang.system.mapper.SysRoleMapper;
import com.zhengshang.system.mapper.SysUserMapper;
import com.zhengshang.system.mapper.SysUserPostMapper;
import com.zhengshang.system.mapper.SysUserRoleMapper;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private AppSigninRecordMapper appSigninRecordMapper;

    @Autowired
    private AppBalanceRecordMapper appBalanceRecordMapper;

    @Autowired
    private AppCashingRecordMapper appCashingRecordMapper;

    @Autowired
    private AppAdvertisementRecordMapper appAdvertisementRecordMapper;
    @Autowired
    private AppContributionRecordMapper appContributionRecordMapper;

    @Autowired
    private IAppSigninRecordService signinRecordService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        if (UserConstants.USER_TYPE_SYS.equals(user.getUserType())) {
            // 新增用户岗位关联
            insertUserPost(user);
        }
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            // 删除用户与角色关联
            userRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            insertUserRole(user);
            Long roleId = user.getRoleIds()[0];
            if (roleId.equals(109L)) {
                user.setAppMemberType("2");
            }
            if (roleId.equals(110L)) {
                user.setAppMemberType("3");
            }
            if (roleId.equals(111L)) {
                user.setAppMemberType("1");
            }
        }
        if (user.getPostIds() != null && user.getPostIds().length > 0) {
            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);
        }
        return userMapper.updateUser(user);
    }

    @Override
    public int updateDeviceID(SysUser user) {
        return userMapper.updateDeviceID(user);
    }

    @Override
    public List<String> getDeviceIDNum(String deviceID) {
        return userMapper.getDeviceIDNum(deviceID);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUserStatus(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    @Override
    public int updateUserNickName(SysUser user) {
        return userMapper.updateUserNickName(user);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }


    /**
     * 更新贡献值
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateContributionValue(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改所属合伙人
     */
    @Override
    public int changePartner(SysUser user) {
        String userName = user.getUserName();
        SysUser p = selectUserByUserName(userName);
        SysUser update = new SysUser();
        update.setUserId(user.getUserId());
        update.setPertainToPartnerId(p.getUserId());
        return userMapper.updateUser(update);
    }


    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<SysUser> selectUserList(SysUser user, Long[] userIds) {
        return userMapper.selectUserListExclude(user, userIds);
    }

    @Override
    public SysUser getUserByPromoCode(String promoCode) {
        SysUser sysUser = userMapper.getUserByPromoCode(promoCode);
        if (sysUser == null || sysUser.getUserId() == null)
            return null;
        return sysUser;
    }

    @Override
    public List<SysUser> queryMyTeam(SysUser user) {
        return userMapper.queryMyTeam(user);
    }

    @Override
    public int queryMyTeamNum(SysUser user) {
        return userMapper.queryMyTeamNum(user);
    }

    @Override
    public List<SysUser> memberList(SysUser user) {
        return userMapper.memberList(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginAppUser appSignin(LoginAppUser loginAppUser, AppAdvertisementRecord appAdvertisementRecord) throws Exception {
        try {
            String signinMoneyStr = configService.selectConfigByKey("app.signin.money");
            if (StringUtils.isBlank(signinMoneyStr)) {
                signinMoneyStr = "0.05";
            }

            Long userId = loginAppUser.getAppUser().getUserId();
            SysUser sysUser = selectUserById(userId);
            if (ObjectUtils.isNotEmpty(sysUser)) {
                Integer signCount = ObjectUtils.isNotEmpty(sysUser.getSignCount()) ? sysUser.getSignCount() : 0;
                if (signCount > 100) {
                    String money2 = configService.selectConfigByKey("app.signin.money2", "0.03");
                    signinMoneyStr = money2;
                }
                if (signCount > 200) {
                    String money3 = configService.selectConfigByKey("app.signin.money3", "0.01");
                    signinMoneyStr = money3;
                }
            }

            BigDecimal signinMoney = new BigDecimal(signinMoneyStr);

            //1、签到记录
            AppSigninRecord appSigninRecord = signinRecordService.getUpperAppSigninRecord(userId, DateUtils.dateTime());
            if (ObjectUtils.isEmpty(appSigninRecord)) {
                appSigninRecord = new AppSigninRecord();
                appSigninRecord.setUserId(loginAppUser.getAppUser().getUserId());
                appSigninRecord.setSigninDate(DateUtils.dateTime());
                appSigninRecord.setRewardCoin(new BigDecimal(signinMoneyStr));
                appSigninRecord.setCreateBy(loginAppUser.getAppUser().getUserName());
                appSigninRecord.setDelFlag(UserStatus.OK.getCode());
                appSigninRecord.setSigninCount(1);
                if (loginAppUser.getAppUser().getUserId().equals(2618L) || loginAppUser.getAppUser().getUserId().equals(1092L)) {
                    appSigninRecord.setSigninCount(10);
                    BigDecimal rewardCoin = new BigDecimal(signinMoneyStr).multiply(new BigDecimal(appSigninRecord.getSigninCount()));
                    appSigninRecord.setRewardCoin(rewardCoin);
                }
                appSigninRecord.setCreateTime(DateUtils.getNowDate());
                AppSigninRecord upperRecord = appSigninRecordMapper.getUpperAppSigninRecord(appSigninRecord.getUserId(), DateUtils.dateCalculationDay(-1, "yyyyMMdd"));
                if (upperRecord != null) {
                    //连续签到
                    appSigninRecord.setSigninContinuityDays(upperRecord.getSigninContinuityDays() + 1);
                } else {
                    //中断签到
                    appSigninRecord.setSigninContinuityDays(1);
                }
                appSigninRecord.setAdvertisementRecordId(appAdvertisementRecord.getRecordId());
                appSigninRecordMapper.insertAppSigninRecord(appSigninRecord);
            } else {
                Integer count = appSigninRecord.getSigninCount() == null ? 1 : appSigninRecord.getSigninCount();
                if (count >= 10) {
                    return loginAppUser;
                }
                appSigninRecord.setSigninCount(count + 1);
                BigDecimal rewardCoin = new BigDecimal(signinMoneyStr).multiply(new BigDecimal(appSigninRecord.getSigninCount()));
                appSigninRecord.setRewardCoin(rewardCoin);
                appSigninRecordMapper.updateAppSigninRecord(appSigninRecord);
            }
            //签到次数
            Integer signinCount = appSigninRecord.getSigninCount();
            //2、金币、记录等
            SysUser user = userMapper.selectUserById(loginAppUser.getAppUser().getUserId());
            Date date = DateUtils.getNowDate();
            insertAppBalanceRecord(loginAppUser, user, signinMoney, date);
            if (signinCount.equals(10)) {
                //给上级用户返利
                if (ObjectUtils.isNotEmpty(sysUser.getUpUserId())) {
                    SysUser upSysUser = userMapper.selectUserById(sysUser.getUpUserId());
                    updateUserBalance(upSysUser, new BigDecimal("0.02"), "来自于下级用户<" + sysUser.getUserName() + ">的签到收益返利", AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER);
                }
                if (ObjectUtils.isNotEmpty(sysUser.getUpUpUserId())) {
                    SysUser upupSysUser = userMapper.selectUserById(sysUser.getUpUpUserId());
                    updateUserBalance(upupSysUser, new BigDecimal("0.01"), "来自于下下级用户<" + sysUser.getUserName() + ">的签到收益返利", AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER_LOWER);
                }
            }

            //4、广告观看记录状态变更
            appAdvertisementRecord.setState("3");
            appAdvertisementRecord.setUpdateBy(loginAppUser.getUsername());
            appAdvertisementRecord.setUpdateTime(DateUtils.getNowDate());
            appAdvertisementRecordMapper.updateAppAdvertisementRecord(appAdvertisementRecord);
            return loginAppUser;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("签到失败，错误信息：{}", e.getMessage());
            throw new Exception("签到失败");
        }
    }

    private void insertAppBalanceRecord(LoginAppUser loginAppUser, SysUser user, BigDecimal signinMoney, Date data) {

        user.setAppAccountBalance(user.getAppAccountBalance().add(signinMoney));
        user.setUpdateBy(user.getUserName());
        userMapper.updateUserAccountBalance(user);
        loginAppUser.setAppUser(user);

        //3、增加余额变动记录
        AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
        appBalanceRecord.setMoney(signinMoney);
        appBalanceRecord.setUserId(loginAppUser.getAppUser().getUserId());
        appBalanceRecord.setModifyAfterBalance(user.getAppAccountBalance());
        appBalanceRecord.setModifyType(AppConstant.BALANCE_ADD);
        appBalanceRecord.setModifySource(AppConstant.MODIFY_SOURCE_SIGNIN);
        appBalanceRecord.setCreateBy(loginAppUser.getUsername());
        appBalanceRecord.setCreateTime(data);
        appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);
    }

    @Override
    public LoginAppUser updateRole(LoginAppUser loginAppUser, String roleKey) {
        SysRole sysRole = roleMapper.checkRoleKeyUnique(roleKey);
        // 新增用户与角色管理
        SysUser sysUser = loginAppUser.getAppUser();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
        sysUser.setRoleIds(new Long[]{sysRole.getRoleId()});
        insertUserRole(sysUser);
        //购买星级会员赠送优惠券
        if (roleKey.equals("mem_member")) {
            String couponCount = configService.selectConfigByKey("app.coupon.count");
            Integer count = ObjectUtils.isNotEmpty(couponCount) ? Integer.parseInt(couponCount) : 0;
            sysUser.setCouponCount(count);
        }
        userMapper.updateUser(sysUser);
        return loginAppUser;
    }

    @Transactional
    @Override
    public boolean buyMember(SysUser sysUser, Long upUserId, String member, AppDefaultParam appDefaultParam) {
        if (upUserId == null) {
            return false;
        }
        SysUser upUser = userMapper.selectUserById(upUserId);//上级账户
        SysUser partnerUser = getPartnerUser(sysUser);//所属合伙人用户
//        //如果上级账户已开通合伙人
//        if ("1".equals(upUser.getIsPartner())) {
//            //更新用户所属合伙人的ID
//            sysUser.setPertainToPartnerId(upUserId);
//            partnerUser = upUser;//所属合伙人用户
//        } else if (upUser.getPertainToPartnerId() != null) {
//            //如果上级用户不是合伙人，更新为上级用户的所属合伙人
//            sysUser.setPertainToPartnerId(upUser.getPertainToPartnerId());
//            partnerUser = userMapper.selectUserById(upUser.getPertainToPartnerId());
//        }

        //要奖励的贡献值数量
        BigDecimal contribution = new BigDecimal(0);

        if (AppConstant.ORDERNUM_PREFIX_MEMBER.equals(member)) {//如果是购买星级会员，无需判断其直推用户的会员类型，直接返现
            Integer childNum = upUser.getChildNum() != null ? upUser.getChildNum() : 0;
            String maxNum = configService.selectConfigByKey("app.buymem.up.day", "0");
            Integer num = Integer.parseInt(maxNum);
            if ((childNum + 1) % num == 0 && childNum > 0) {
                BigDecimal amount = new BigDecimal(configService.selectConfigByKey("app.buymem.up.bonus2"));
                appDefaultParam.setBuyMemUpBonus(amount.add(appDefaultParam.getBuyMemUpBonus()));
            }
            //更新用户余额
            upUser.setAppAccountBalance(upUser.getAppAccountBalance().add(appDefaultParam.getBuyMemUpBonus()));
            upUser.setChildNum(childNum + 1);
            userMapper.updateUser(upUser);
            //增加余额变动记录
            AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
            appBalanceRecord.setMoney(appDefaultParam.getBuyMemUpBonus());
            appBalanceRecord.setUserId(upUser.getUserId());
            appBalanceRecord.setModifyAfterBalance(upUser.getAppAccountBalance());
            appBalanceRecord.setModifyType(AppConstant.BALANCE_ADD);
            appBalanceRecord.setModifySource(AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER);
            appBalanceRecord.setCreateBy(upUser.getUserName());
            appBalanceRecord.setCreateTime(DateUtils.getNowDate());
            appBalanceRecord.setRemark("来自于下级用户<" + sysUser.getUserName() + ">的【星级会员】返利");
            appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);

            contribution = new BigDecimal(AppConstant.APP_CONTRIBUTION_MEMBER);
        } else if (AppConstant.ORDERNUM_PREFIX_VIP.equals(member)) {//如果是购买VIP会员，需要判断其直推和间推用户的会员类型，如果是星级会员，将其返佣金额冻结

            switch (upUser.getAppMemberType()) {
                case UserConstants.APP_MEMBER_TYPE_MEM://直推用户如果是星级会员，增加冻结佣金
                    //增加冻结金额
                    upUser.setAppFrozenCommission(upUser.getAppFrozenCommission().add(appDefaultParam.getBuyvipUpBonus()));
                    userMapper.updateUser(upUser);
                    break;
                case UserConstants.APP_MEMBER_TYPE_VIP://直推用户如果是VIP，直接返佣到账
                    //更新上级用户的余额
                    updateUserBalance(upUser, appDefaultParam.getBuyvipUpBonus(), "来自于下级用户<" + sysUser.getUserName() + ">的【VIP会员】返利", AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER);
                    break;
            }

            SysUser upupUser = userMapper.selectUserById(upUser.getUpUserId());
            if (upupUser != null && upUser.getUpUserId() != null) {
                //获取间推用户
                switch (upupUser.getAppMemberType()) {
                    case UserConstants.APP_MEMBER_TYPE_MEM://间推用户如果是星级会员，增加冻结佣金
                        //增加冻结金额
                        upupUser.setAppFrozenCommission(upupUser.getAppFrozenCommission().add(appDefaultParam.getBuyvipUpUpBonus()));
                        userMapper.updateUser(upupUser);
                        break;
                    case UserConstants.APP_MEMBER_TYPE_VIP://间推用户如果是VIP，直接返佣到账
                        //更新上级用户的余额
                        updateUserBalance(upupUser, appDefaultParam.getBuyvipUpUpBonus(), "来自于下下级用户<" + sysUser.getUserName() + ">的【VIP会员】返利", AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER_LOWER);
                        break;
                }
            }
            contribution = new BigDecimal(AppConstant.APP_CONTRIBUTION_VIP);
        }

        //如果找到相对应的合伙人用户，将其贡献值增加
        if (partnerUser != null) {

            sysUser.setUpdateBy(partnerUser.getUserName());
            sysUser.setUpdateTime(DateUtils.getNowDate());
            sysUser.setPertainToPartnerId(partnerUser.getUserId());
            //绑定所属合伙人
            userMapper.bandPartnerId(sysUser);
            //增加所属合伙人的贡献值
            partnerUser.setContributionValue(partnerUser.getContributionValue().add(contribution));
            //更新用户所属合伙人的贡献值
            userMapper.plusContributionValue(partnerUser);

            //增加贡献值记录
            AppContributionRecord appContributionRecord = new AppContributionRecord();
            appContributionRecord.setUserId(partnerUser.getUserId());
            appContributionRecord.setFromUserId(sysUser.getUserId());
            appContributionRecord.setContributionNum(contribution);
            appContributionRecord.setCreateBy(sysUser.getUserName());
            appContributionRecord.setCreateTime(DateUtils.getNowDate());
            appContributionRecordMapper.insertAppContributionRecord(appContributionRecord);
        }
        return true;
    }

    /**
     * 更新上级用户余额
     *
     * @param user
     * @param amount
     * @param remark
     * @param modifySource
     */
    @Override
    public void updateUserBalance(SysUser user, BigDecimal amount, String remark, String modifySource) {
        //更新上级用户的余额
        user.setAppAccountBalance(user.getAppAccountBalance().add(amount));
        userMapper.updateUser(user);
        //增加余额变动记录：下级会员收益
        AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
        appBalanceRecord.setMoney(amount);
        appBalanceRecord.setUserId(user.getUserId());
        appBalanceRecord.setModifyAfterBalance(user.getAppAccountBalance());
        appBalanceRecord.setModifyType(AppConstant.BALANCE_ADD);
        appBalanceRecord.setModifySource(modifySource);
        appBalanceRecord.setCreateBy(user.getUserName());
        appBalanceRecord.setCreateTime(DateUtils.getNowDate());
        appBalanceRecord.setRemark(remark);
        appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);
    }

    private SysUser getPartnerUser(SysUser sysUser) {
        if (sysUser.getUpUserId() == null) {
            return null;
        }
        if ("1".equals(sysUser.getIsPartner())) {
            return null;
        }
        SysUser upSysUser = userMapper.selectUserById(sysUser.getUpUserId());
        if ("1".equals(upSysUser.getIsPartner())) {
            return upSysUser;
        }
        //如果上级用户
        if (upSysUser.getPertainToPartnerId() != null) {
            return userMapper.selectUserById(upSysUser.getPertainToPartnerId());
        }
        return getPartnerUser(upSysUser);
    }

    @Transactional
    @Override
    public SysUser withdrawal(SysUser appUser, AppCashingRecord appCashingRecord) {
        appUser.setAppAccountBalance(appUser.getAppAccountBalance().subtract(appCashingRecord.getCashingMoney()));
        appUser.setAppFrozenAmount(appUser.getAppFrozenAmount().add(appCashingRecord.getCashingMoney()));
        appUser.setUpdateBy(appUser.getUserName());
        userMapper.updateUser(appUser);

        //增加余额变动记录
        AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
        appBalanceRecord.setMoney(appCashingRecord.getCashingMoney());
        appBalanceRecord.setUserId(appUser.getUserId());
        appBalanceRecord.setModifyAfterBalance(appUser.getAppAccountBalance());
        appBalanceRecord.setModifyType(AppConstant.BALANCE_REDUCE);
        appBalanceRecord.setModifySource(AppConstant.MODIFY_SOURCE_WITHDRAWAL_APPLY);
        appBalanceRecord.setCreateBy(appUser.getUserName());
        appBalanceRecord.setCreateTime(DateUtils.getNowDate());
        appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);

        //提现记录
        appCashingRecord.setCreateBy(appUser.getUserName());
        appCashingRecord.setCreateTime(DateUtils.getNowDate());
        appCashingRecord.setUserId(appUser.getUserId());
        appCashingRecord.setUserName(appUser.getUserName());
        appCashingRecordMapper.insertAppCashingRecord(appCashingRecord);
        return appUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginAppUser withdrawalFulishe(LoginAppUser loginAppUser, BigDecimal money) throws Exception {
        try {

            //1、余额变动
            SysUser sysUser = userMapper.selectUserById(loginAppUser.getAppUser().getUserId());
            sysUser.setAppAccountBalance(sysUser.getAppAccountBalance().add(money));
            sysUser.setUpdateBy(loginAppUser.getUsername());
            userMapper.updateUserAccountBalance(sysUser);
            loginAppUser.setAppUser(sysUser);

            //2、增加余额变动记录
            AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
            appBalanceRecord.setMoney(money);
            appBalanceRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appBalanceRecord.setModifyAfterBalance(loginAppUser.getAppUser().getAppAccountBalance());
            appBalanceRecord.setModifyType(AppConstant.BALANCE_ADD);
            appBalanceRecord.setModifySource(AppConstant.MODIFY_SOURCE_FULISHE);
            appBalanceRecord.setCreateBy(loginAppUser.getUsername());
            appBalanceRecord.setCreateTime(DateUtils.getNowDate());
            appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);
            return loginAppUser;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("福利社福豆提现到余额失败，错误信息：{}", e.getMessage());
            throw new Exception("福利社福豆提现到余额失败");
        }
    }

    @Override
    public int openingPartner(SysUser user) {
        user.setIsPartner("1");
        user.setUpUserId(142L);
        user.setContributionValue(new BigDecimal(0));
        SysUser query = new SysUser();
        query.setUpUserId(user.getUserId());
        List<SysUser> myUser = userMapper.selectUserList(query);
        //更新所属合伙人
        if (ObjectUtils.isNotEmpty(myUser)) {
            for (SysUser sysUser : myUser) {
                sysUser.setUpUpUserId(142L);
                userMapper.updateUser(sysUser);
            }
        }
        updatePartner(user.getUserId(), user.getUserId());
        return userMapper.openingPartner(user);
    }

    private void updatePartner(Long upUserId, Long userId) {
        SysUser query = new SysUser();
        query.setUpUserId(upUserId);
        List<SysUser> myUser = userMapper.selectUserList(query);
        //更新所属合伙人
        if (ObjectUtils.isNotEmpty(myUser)) {
            for (SysUser sysUser : myUser) {
                sysUser.setPertainToPartnerId(userId);
                userMapper.updateUser(sysUser);
                updatePartner(sysUser.getUserId(), userId);
            }
        }

    }

    @Override
    public int updateAppUser(SysUser user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int thawCommission(SysUser user) {
        try {
            if (user.getAppFrozenCommission() != null) {
                //余额变动记录
                AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
                appBalanceRecord.setMoney(user.getAppFrozenCommission());
                appBalanceRecord.setUserId(user.getUserId());
                appBalanceRecord.setModifyAfterBalance(user.getAppAccountBalance());
                appBalanceRecord.setModifyType(AppConstant.BALANCE_ADD);
                appBalanceRecord.setModifySource(AppConstant.MODIFY_SOURCE_COMMISSION_THAW);
                appBalanceRecord.setCreateBy(user.getUserName());
                appBalanceRecord.setCreateTime(DateUtils.getNowDate());
                appBalanceRecordMapper.insertAppBalanceRecord(appBalanceRecord);
                user.setAppAccountBalance(user.getAppAccountBalance().add(user.getAppFrozenCommission()));
                user.setAppFrozenCommission(new BigDecimal(0));
                return userMapper.thawCommission(user);
            }
        } catch (Exception e) {
            log.error("<userService.thawCommission>解冻冻结佣金失败，{}", e.getMessage());
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void updateTwoUserBalance(SysUser sysUser, BigDecimal commissionAmount, String title) {
        BigDecimal upUserProportion = new BigDecimal(0.7);
        BigDecimal upUsercommissionAmount = commissionAmount.multiply(upUserProportion);
        String upRemark = "来自于下级用户<" + sysUser.getUserName() + ">的" + title + "返利";
        SysUser upUser = selectUserById(sysUser.getUpUserId());//上级账户
        if(ObjectUtils.isNotEmpty(upUser)) {
            updateUserBalance(upUser, upUsercommissionAmount, upRemark, AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER);
        }
        Long upupUserId = sysUser.getUpUpUserId();
        SysUser upupUser = selectUserById(upupUserId);
        if (ObjectUtils.isNotEmpty(upupUser)) {
            BigDecimal upupUserProportion = new BigDecimal(0.3);
            BigDecimal upupUsercommissionAmount = commissionAmount.multiply(upupUserProportion);
            String upupRemark = "来自于下下级用户<" + sysUser.getUserName() + ">的" + title + "返利";
            updateUserBalance(upupUser, upupUsercommissionAmount, upupRemark, AppConstant.MODIFY_SOURCE_WITHDRAWAL_LOWER_LOWER);
        }
    }

    public static void main(String[] args) {
        System.out.println(51 % 10);
    }


}
